package com.bruce.asurada.sso.controller;

import com.bruce.asurada.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

/**
 * 健康检查控制器
 * 
 * @author Bruce
 */
@Slf4j
@RestController
@RequestMapping("/health")
public class HealthController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 整体健康检查
     */
    @GetMapping("/check")
    public Result<Map<String, Object>> healthCheck() {
        Map<String, Object> status = new HashMap<>();
        
        boolean mysqlStatus = checkMysqlConnection();
        boolean redisStatus = checkRedisConnection();
        
        status.put("mysql", mysqlStatus ? "UP" : "DOWN");
        status.put("redis", redisStatus ? "UP" : "DOWN");
        status.put("overall", (mysqlStatus && redisStatus) ? "UP" : "DOWN");
        status.put("timestamp", System.currentTimeMillis());
        
        if (mysqlStatus && redisStatus) {
            return Result.success("系统健康状态良好", status);
        } else {
            return Result.error(500, "系统存在连接问题");
        }
    }

    /**
     * MySQL连接检查
     */
    @GetMapping("/mysql")
    public Result<Map<String, Object>> checkMysql() {
        Map<String, Object> mysqlInfo = new HashMap<>();
        
        try (Connection connection = dataSource.getConnection()) {
            if (connection != null && !connection.isClosed()) {
                mysqlInfo.put("status", "UP");
                mysqlInfo.put("url", connection.getMetaData().getURL());
                mysqlInfo.put("driver", connection.getMetaData().getDriverName());
                mysqlInfo.put("version", connection.getMetaData().getDatabaseProductVersion());
                mysqlInfo.put("catalog", connection.getCatalog());
                
                return Result.success("MySQL连接正常", mysqlInfo);
            } else {
                mysqlInfo.put("status", "DOWN");
                mysqlInfo.put("error", "连接已关闭");
                return Result.error("MySQL连接异常");
            }
        } catch (Exception e) {
            log.error("MySQL连接检查失败: {}", e.getMessage());
            mysqlInfo.put("status", "DOWN");
            mysqlInfo.put("error", e.getMessage());
            return Result.error("MySQL连接失败: " + e.getMessage());
        }
    }

    /**
     * Redis连接检查
     */
    @GetMapping("/redis")
    public Result<Map<String, Object>> checkRedis() {
        Map<String, Object> redisInfo = new HashMap<>();
        
        try {
            // 测试Redis连接
            String testKey = "health_check_" + System.currentTimeMillis();
            redisTemplate.opsForValue().set(testKey, "test");
            String testValue = (String) redisTemplate.opsForValue().get(testKey);
            redisTemplate.delete(testKey);
            
            if ("test".equals(testValue)) {
                redisInfo.put("status", "UP");
                
                // 获取Redis信息
                try {
                    String info = redisTemplate.getConnectionFactory()
                        .getConnection()
                        .serverCommands()
                        .info("server")
                        .getProperty("redis_version");
                    redisInfo.put("version", info);
                } catch (Exception e) {
                    redisInfo.put("version", "未知");
                }
                
                return Result.success("Redis连接正常", redisInfo);
            } else {
                redisInfo.put("status", "DOWN");
                redisInfo.put("error", "读写测试失败");
                return Result.error("Redis连接异常");
            }
        } catch (Exception e) {
            log.error("Redis连接检查失败: {}", e.getMessage());
            redisInfo.put("status", "DOWN");
            redisInfo.put("error", e.getMessage());
            return Result.error("Redis连接失败: " + e.getMessage());
        }
    }

    /**
     * 检查MySQL连接状态
     */
    private boolean checkMysqlConnection() {
        try (Connection connection = dataSource.getConnection()) {
            return connection != null && !connection.isClosed();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 检查Redis连接状态
     */
    private boolean checkRedisConnection() {
        try {
            String testKey = "connection_test_" + System.currentTimeMillis();
            redisTemplate.opsForValue().set(testKey, "test");
            String testValue = (String) redisTemplate.opsForValue().get(testKey);
            redisTemplate.delete(testKey);
            return "test".equals(testValue);
        } catch (Exception e) {
            return false;
        }
    }
}